package com.pangda.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.pangda.common.domain.PageResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 文件工具类
 */
public class FileUtil {

    //无填充方式导出并下载xlsx

    /**
     * 导出下载文件
     *
     * @param excelName 文件名
     * @param response  响应体
     * @param cla       要导出的对象类型
     * @param list      要导出的对象列表
     * @throws IOException io异常
     */
    public static void downloadUnfilledToXlsx(String excelName, HttpServletResponse response, Class cla, List list) throws IOException {
        // 这里注意 使用swagger 会导致各种问题，easyexcel官方文档推荐直接用浏览器或者用postman测试
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), cla).sheet(excelName).doWrite(list);
    }

    //
    public static Map<String, String> uploadFile(List list, Class clazz, RedisTemplate redisTemplate) {
        Map<String, Object> map = new HashMap<>();
        map.put("class", clazz.getCanonicalName());
        map.put("data", JSONUtil.toJsonStr(list));
        String fileName = UUID.randomUUID() + "";
        redisTemplate.opsForValue().set(fileName, JSONUtil.toJsonStr(map), 60, TimeUnit.SECONDS);
        Map<String, String> result = new HashMap<>();
        result.put("msg", fileName);
        return result;
    }

    /**
     * 导出文件
     *
     * @param pathName 文件的完整路径
     * @param list     要导出的对象列表
     * @param clazz    要导出的对象类型
     * @param <T>      要导出的对象类型
     */
    public static <T> void writeFile(String pathName, List<T> list, Class<T> clazz) {
        EasyExcel.write(pathName)
                .head(clazz)
                .excelType(ExcelTypeEnum.XLS)
                .sheet()
                .doWrite(list);
    }


    public static <T> List<T> readExcel(InputStream inputStream, Class<T> clazz) {
        // excelTypeEnum 根据实际的Excel类型填写，例如 ExcelTypeEnum.XLSX
        ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.XLSX;
        List<T> list = new LinkedList<>();

        EasyExcel.read(inputStream, clazz, new AnalysisEventListener<T>() {
                    @Override
                    public void invoke(T t, AnalysisContext analysisContext) {
                        list.add(t);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        System.out.println("读取完毕！");
                    }
                })
                .excelType(excelTypeEnum)
                .sheet() // 默认读取第一个sheet
                .doRead();
        return list;
    }


    /**
     * 获取模板
     *
     * @param response 响应体
     * @param clazz    要导出的对象类型
     * @throws IOException io异常
     */
    public static void getTemplate(HttpServletResponse response, String excelName, Class clazz) throws IOException {
        // 这里注意 使用swagger 会导致各种问题，easyexcel官方文档推荐直接用浏览器或者用postman测试
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(excelName).doWrite(new LinkedList<>());
    }
}
